﻿using System;
using Common.Entities;
using Common.Exceptions;
using Common.Utils.Constants;
using DataAccess.Accessors.Interfaces;
using DataAccess.Repository.Interfaces;

namespace DataAccess.Repository
{
    public class SecurityKeyRepository : ISecurityKeyRepository
    {
        private readonly ISecurityKeyAccessor _securityKeyAccessor;
        private readonly IUserAccessor _userAccessor;

        public SecurityKeyRepository(ISecurityKeyAccessor securityKeyAccessor, IUserAccessor userAccessor)
        {
            _securityKeyAccessor = securityKeyAccessor;
            _userAccessor = userAccessor;
        }

        public long GetUserIdBySecurityKey(SecurityKey securityKey)
        {
            try
            {
                var securityKeyDao = _securityKeyAccessor.GetSecurityKeyDAO(securityKey.SecurityKeyValue);
                return securityKeyDao.UserId;
            }
            catch (Exception innerException)
            {
                throw new DataAccessException(ExceptionMessage.DataAccessException, innerException);
            }
        }

        public SecurityKey GetSecurityKeyForUser(User user)
        {
            throw new NotImplementedException();
        }

        public void SaveSecurityKeyForUser(User user)
        {
            var userDao = _userAccessor.GetUser(user.UserName);
            if(userDao != null)
            {
                _securityKeyAccessor.SaveSecurityKeyForUser(userDao.UserId, user.SecurityKey.SecurityKeyValue);
            }
        }

        public bool RemoveSecurityKey(User user)
        {
            var removed = false;
            try
            {
                var userDao = _userAccessor.GetUser(user.UserName);
                if (userDao != null)
                {
                    _securityKeyAccessor.RemoveSecurityKeyForUser(userDao.UserId, user.SecurityKey.SecurityKeyValue);
                    removed = true;
                }
            }
            catch (Exception innerException)
            {
                throw new DataAccessException(ExceptionMessage.DataAccessException, innerException);
            }
            return removed;
        }
    }
}
